<?php
class ForumComments extends CActiveRecord {
    
    public $comId;
    public $themeId;
    public $userId;
    public $comDate;
    public $text;
    public $userIp;
    
    public $deletedImg;
    public $subscrEmail;
    public $subscr;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'forum_comments';
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if($this->getIsNewRecord()) {
            $this->comDate = time();
            $this->userId = Yii::app()->user->isGuest ? 0 : Yii::app()->user->getId();
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip=$_SERVER['HTTP_CLIENT_IP'];
            elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
            else $ip=$_SERVER['REMOTE_ADDR'];
            $this->userIp = $ip;
            if(!empty($this->subscrEmail) || $this->subscr) {
                $this->subscrEmail = $this->subscr ? Yii::app()->user->getState('email') : $this->subscrEmail;
                $exists = Yii::app()->db->createCommand('select 1 from subscribers where type="forum_topic" and typeId='.$this->themeId.' and email="'.$this->subscrEmail.'" limit 1')->queryScalar();
                if(!$exists) {
                    if(Yii::app()->user->isGuest) {
                        Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'forum_topic', 'typeId'=>$this->themeId, 'email'=>$this->subscrEmail, 'userId'=>'0', 'date'=>time() ));
                    } else {
                        Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'forum_topic', 'typeId'=>$this->themeId, 'email'=>Yii::app()->user->getState('email'), 'date'=>time(), 'userId'=>Yii::app()->user->getId() ));
                    }
                } elseif($this->subscr) Yii::app()->db->createCommand()->update ('subscribers', array('userId'=>Yii::app()->user->getId()));
            }
        } else {
            if(!empty($this->deletedImg)) {
                $images = explode(',', $this->deletedImg);
                Yii::app()->db->createCommand()->delete('forum_images', '`smallImg` in("'.str_replace(',', '","', $_POST['ForumComments']['deletedImg']).'")');
                for($i=0; $i<count($images); $i++) {
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$images[$i]))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$images[$i]);
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.str_replace('sm', '', $images[$i])))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.str_replace('sm', '', $images[$i]));
                }
            }
        }
        return true;
    }
        
    public function rules() {
        return array(
            array('text, themeId', 'required', 'message' => '{attribute} не может быть пустым'),
            array('themeId', 'numerical', 'integerOnly'=>true, 'min'=>1),
            array('subscrEmail', 'email', 'message'=>'Введенный вами email содержит ошибки'),
            array('deletedImg, subscr', 'safe')
        );
    }
    
    public function relations() {
        return array(
            'comUser' => array(self::BELONGS_TO, 'User', array('userId'=>'userid')),
            'comImg' => array(self::HAS_MANY, 'ForumImages', 'comId')
        );
    }
    
    public function afterSave() {
        $partnerId = Yii::app()->db->createCommand()->select('partnerId')->from('forum_theme')->where('themeId='.$this->themeId)->queryRow();
        Yii::app()->db->createCommand('UPDATE `partners` SET `countComments`=countComments + 1 WHERE `partnerid`="'.$partnerId['partnerId'].'"')->query();
        Yii::app()->db->createCommand('UPDATE `forum_theme` SET `countComments`=countComments + 1 WHERE `themeId`='.$this->themeId)->query();
        $userFiles = Yii::app()->user->getState('xuploadFiles', array());
        if(!empty($userFiles)) {
            foreach ($userFiles as $k=>$v) {
                $this->changeImage($k);                    
                Yii::app()->db->createCommand()->update('forum_images', array('comId'=>$this->primaryKey, 'smallImg'=>'sm'.$k), 'bigImg = :bigName', array(':bigName'=>$k));
            }
        }
        Yii::app()->db->createCommand()->insert('mailer_auto', array('type'=>'forum_topic', 'typeId'=>$this->themeId, 'childId'=>$this->primaryKey, 'date'=>time()));
    }
    
    private function changeImage($img) {
        if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)) return 0;
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)
            ->watermark($_SERVER['DOCUMENT_ROOT'] . '/images/prettyImg/watermark.png', 10, 20, CImageHandler::CORNER_CENTER, 0.3)
            ->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img);
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/'.$img)
            ->resize(80, 80)
            ->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/comments/sm'.$img);
    }
    
    public function pagination($limit, $offset) {
        $this->getDbCriteria()->mergeWith(array(
            'offset' => $offset,
            'limit' => $limit,
        ));
        return $this;
    }
    
    public function beforeValidate() {
        if(!parent::beforeValidate()) return false;
        $this->attributes = !empty($_POST[get_class($this)]) ? $_POST[get_class($this)] : array();
        return true;
    }
}
